package com.example.cursor_service.impl;

import com.example.cursor_service.AuthService;
import com.example.cursor_orm.dao.RoleDAO;
import com.example.cursor_orm.dao.PermissionDAO;
import com.example.cursor_orm.model.Role;
import com.example.cursor_orm.model.Permission;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;

@Service
public class AuthServiceImpl implements AuthService {
    private final RoleDAO roleDAO;
    private final PermissionDAO permissionDAO;
    
    public AuthServiceImpl(RoleDAO roleDAO, PermissionDAO permissionDAO) {
        this.roleDAO = roleDAO;
        this.permissionDAO = permissionDAO;
    }
    
    @Override
    public boolean checkUserPermission(Integer userId, String permissionName) {
        try {
            // 通过用户ID查找权限，检查是否包含指定权限
            List<Permission> permissions = permissionDAO.findByUserId(userId);
            return permissions.stream().anyMatch(p -> p.getName().equals(permissionName));
        } catch (Exception e) {
            // 如果数据库操作失败，返回false
            return false;
        }
    }
    
    @Override
    public List<String> getUserPermissions(Integer userId) {
        try {
            List<String> perms = new ArrayList<>();
            List<Permission> permissions = permissionDAO.findByUserId(userId);
            permissions.forEach(p -> perms.add(p.getName()));
            return perms;
        } catch (Exception e) {
            return new ArrayList<>();
        }
    }
    
    @Override
    public boolean checkUserRole(Integer userId, String roleName) {
        try {
            // 通过用户ID查找角色，检查是否包含指定角色
            List<Role> roles = roleDAO.findByUserId(userId);
            return roles.stream().anyMatch(r -> r.getName().equals(roleName));
        } catch (Exception e) {
            return false;
        }
    }
    
    @Override
    public List<String> getUserRoles(Integer userId) {
        try {
            List<String> roles = new ArrayList<>();
            List<Role> userRoles = roleDAO.findByUserId(userId);
            userRoles.forEach(r -> roles.add(r.getName()));
            return roles;
        } catch (Exception e) {
            return new ArrayList<>();
        }
    }
} 